<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="区域">
              <el-cascader
                v-model="searchForm.areaId"
                :options="areaOptions"
                :props="areaProps"
                clearable
                :placeholder="areaLoading ? '正在加载数据...' : areaOptions.length === 0 ? '暂无数据' : '请选择客户 -> 站点 -> 区域'"
                filterable
                :show-all-levels="true"
                :separator="' / '"
                collapse-tags
                collapse-tags-tooltip
                :loading="areaLoading"
                style="width: 200px;"
              />
            </el-form-item>
            <el-form-item label="设备状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option label="在线" value="online" />
                <el-option label="离线" value="offline" />
              </el-select>
            </el-form-item>
            <el-form-item label="综合搜索">
              <el-input v-model="searchForm.queryString" placeholder="型号/序列号" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch" :loading="searchLoading">
                查询
              </el-button>
              <el-button @click="resetSearch" :disabled="searchLoading">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>

      <el-button 
        type="success" 
        @click="handleAdd" 
        style="margin-bottom: 15px;"
        :loading="addLoading"
      >
        <el-icon><Plus /></el-icon> 新增设备
      </el-button>

      <el-table
        :data="tableData"
        border
        v-loading="tableLoading"
        style="width: 100%;"
      >
        <el-table-column prop="serialNo" label="序列号" width="180" />
        <el-table-column prop="model"    label="设备型号" width="150" />
        <el-table-column prop="currentMeterReading" label="当前抄表读数(吨)" width="150">
          <template #default="{ row }">
            {{ row.currentMeterReading ? row.currentMeterReading.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="lastMonthMeterReading" label="上月抄表读数(吨)" width="150">
          <template #default="{ row }">
            {{ row.lastMonthMeterReading ? row.lastMonthMeterReading.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="status"   label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'online' ? 'success' : 'danger'">
              {{ row.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastHeartbeat" label="最后心跳" width="180">
          <template #default="{ row }">
            {{ formatDate(row.lastHeartbeat) || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="160">
          <template #default="{ row }">
            <el-button size="mini" @click="handleViewData(row)">监控</el-button>
            <el-button size="mini" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        v-model:current-page="pagination.current"
        :page-size="pagination.size"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        layout="prev, pager, next, total"
        :disabled="tableLoading"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import DeviceAPI from '@/api/system/device.api';
import SiteAPI from '@/api/system/site.api';
import { formatDate } from '@/utils/date';

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  areaId: null,
  status: '',
  queryString: '',
});

// 区域级联配置
const areaOptions = ref([]);
const areaProps = {
  label: 'name',
  value: 'id',
  children: 'children',
  checkStrictly: true,
  multiple: false,
};

// 表格数据及状态
const tableData = ref([]);
const tableLoading = ref(false);
const searchLoading = ref(false);
const addLoading = ref(false);
const areaLoading = ref(false);
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
});

// 加载区域列表
const loadAreaOptions = async () => {
  areaLoading.value = true;
  try {
    const res = await SiteAPI.getFullHierarchy();
    
    // request工具已经处理了响应，直接返回data部分
    if (res && Array.isArray(res)) {
      
      // 修复层级结构（临时解决方案）
      const fixHierarchy = (data) => {
        return data.map(customer => {
          const fixedCustomer = { ...customer };
          if (customer.children) {
            fixedCustomer.children = customer.children.map(site => {
              const fixedSite = { ...site };
              if (site.children) {
                // 重新构建区域层级
                const areaMap = new Map();
                const rootAreas = [];
                
                // 创建所有区域节点
                site.children.forEach(area => {
                  areaMap.set(area.id, { ...area, children: [] });
                });
                
                // 构建父子关系 - 基于名称匹配（临时解决方案）
                site.children.forEach(area => {
                  // 如果后端没有提供parentAreaId，尝试基于名称匹配
                  if (!area.parentAreaId || area.parentAreaId === undefined || area.parentAreaId === 0 || area.parentAreaId === '0') {
                    // 检查是否是楼层（包含"层"字）
                    if (area.name.includes('层')) {
                      // 查找可能的父级建筑（包含"栋"字）
                      const possibleParent = site.children.find(a => 
                        a.name.includes('栋') && a.id !== area.id
                      );
                      if (possibleParent) {
                        const parent = areaMap.get(possibleParent.id);
                        if (parent) {
                          parent.children.push(areaMap.get(area.id));
                        } else {
                          rootAreas.push(areaMap.get(area.id));
                        }
                      } else {
                        rootAreas.push(areaMap.get(area.id));
                      }
                    } else {
                      rootAreas.push(areaMap.get(area.id));
                    }
                  } else {
                    // 使用后端提供的parentAreaId
                    const parent = areaMap.get(area.parentAreaId);
                    if (parent) {
                      parent.children.push(areaMap.get(area.id));
                    } else {
                      rootAreas.push(areaMap.get(area.id));
                    }
                  }
                });
                
                fixedSite.children = rootAreas;
              }
              return fixedSite;
            });
          }
          return fixedCustomer;
        });
      };
      
      const fixedData = fixHierarchy(res);
      areaOptions.value = fixedData || [];
    } else {
      console.warn('层级数据为空或格式不正确:', res);
      areaOptions.value = [];
    }
  } catch (error) {
    ElMessage.error('加载层级数据失败');
    console.error('加载层级数据失败:', error);
    console.error('错误详情:', error.response || error);
    areaOptions.value = [];
  } finally {
    areaLoading.value = false;
  }
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.areaId = null;
  searchForm.status = '';
  searchForm.queryString = '';
  pagination.current = 1;
  loadDevices();
};

// 触发搜索
const onSearch = async () => {
  searchLoading.value = true;
  pagination.current = 1;
  await loadDevices();
  searchLoading.value = false;
};

// 加载设备列表
const loadDevices = async () => {
  tableLoading.value = true;
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      status: searchForm.status || undefined,
      areaId: searchForm.areaId?.length
        ? searchForm.areaId[searchForm.areaId.length - 1] // 获取最后一级（区域）的ID
        : undefined,
      queryString: searchForm.queryString || undefined,
    };
    const res = await DeviceAPI.getPage(params);
    tableData.value = res.list || [];
    pagination.total = res.total || 0;
  } catch (error) {
    ElMessage.error('加载设备列表失败: ' + error.message);
    console.error(error);
  } finally {
    tableLoading.value = false;
  }
};

// 分页切换
const handleCurrentChange = (page) => {
  pagination.current = page;
  loadDevices();
};

// 新增设备
const handleAdd = () => {
  addLoading.value = true;
  router.push({ name: 'deviceCreate' });
};

// 编辑设备
const handleEdit = (row) => {
  router.push({ name: 'deviceEdit', params: { id: row.id } });
};

// 删除设备
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定删除设备 ${row.serialNo} 吗？`,
      '删除确认',
      { type: 'warning' }
    );
    await DeviceAPI.deleteById(row.id);
    ElMessage.success('删除成功');
    loadDevices();
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('删除失败');
      console.error(err);
    }
  }
};

// 查看监控数据
const handleViewData = (row) => {
  router.push({ name: 'deviceDetail', params: { id: row.id } });
};

// 初始化
onMounted(() => {
  loadAreaOptions();
  loadDevices();
});
</script>

<style scoped>
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.card-header {
  padding: 10px 0;
}

/* 级联选择器样式优化 */
:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-cascader__tags) {
  flex-wrap: wrap;
}

:deep(.el-cascader__collapse-tags) {
  display: flex;
  align-items: center;
}

/* 加载状态样式 */
:deep(.el-cascader.is-loading .el-cascader__label) {
  color: #c0c4cc;
}
</style>
